package com.banmao.youZone.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.banmao.youZone.consts.CommonConst;
import com.banmao.youZone.entity.Holiday;
import com.banmao.youZone.entity.UserVO;
import com.banmao.youZone.mapper.HolidayMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class HolidayJob {

    @Resource
    private HolidayMapper holidayMapper;

    // @Scheduled(cron = "0 */1 * * * ?", initialDelay = 5000)
    @Scheduled(cron = "0 0 0 * 11-12 7")
    private void execute() {
        log.info("[HolidayJob]execute...");

        DateTime current = DateUtil.date();

        int nextYear = current.year() + 1;

        Long nextYestCount = holidayMapper.selectCount(Wrappers.<Holiday>lambdaQuery()
                .eq(Holiday::getYear, nextYear));

        if (nextYestCount != null && nextYestCount > 0) {
            log.info("[HolidayJob]已获取{}节假日", nextYear);
            return;
        }

        UserVO userVO = new UserVO();
        userVO.setUserId(-99);
        CommonConst.USER_THREAD_LOCAL.set(userVO);

        List<Holiday> holidays = new ArrayList<>();
        try {
            HttpRequest getRequest = HttpUtil.createGet("https://timor.tech/api/holiday/year/" + (nextYear));
            getRequest.timeout(10000);

            log.info("[HolidayJob]request execute prepare...");
            try (HttpResponse response = getRequest.execute()) {
                log.info("[HolidayJob]request executed finish...");
                String json = response.body();

                if (StringUtils.isBlank(json)) {
                    log.error("[HolidayJob]获取{}节假日失败", nextYear);
                    return;
                }

                holidays = Holiday.build(json);
            }
        } catch (Exception e) {
            log.error("[HolidayJob]请求报错,msg:{},error:", e.getMessage(), e);
        } finally {
            CommonConst.USER_THREAD_LOCAL.remove();
        }

        if (CollectionUtils.isEmpty(holidays)) {
            log.error("[HolidayJob]更新{}数据失败", nextYear);
            return;
        }

        holidayMapper.delete(Wrappers.<Holiday>lambdaUpdate().eq(Holiday::getYear, nextYear));

        List<BatchResult> results = holidayMapper.insert(holidays);
        results.forEach(r -> {
            int[] updateCounts = r.getUpdateCounts();
            log.info("[HolidayJob]更新数据:{}", updateCounts.length);
        });

        log.info("[HolidayJob]更新{}节假日完成", nextYear);

    }

}
